<template>
  <div class="shop-manage">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-row>
        <el-form-item label="订单号">
          <el-input v-model="formInline.orderNumber" placeholder="输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="formInline.nickName" placeholder="输入用户昵称" clearable></el-input>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker v-model="formInline.startDate" type="date" placeholder="开始时间" clearable></el-date-picker>
          <el-date-picker v-model="formInline.endDate" type="date" placeholder="结束时间" clearable></el-date-picker>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="订单状态">
          <el-select v-model="formInline.status" placeholder="订单状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option :label="item" :value="index + 1" :key="index + 1" v-for="(item, index) of orderStatus"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="searchShops">搜索</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <el-table
      :data="list"
      v-loading="loading"
      style="width: 100%">
      <el-table-column
        prop="orderNumber"
        label="订单号"
        width="80">
      </el-table-column>
      <el-table-column
        prop="nickName"
        label="用户昵称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="shopName"
        label="商品名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="payTotal"
        label="支付金额">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="下单时间">
      </el-table-column>
      <el-table-column
        prop="statusWord"
        label="订单状态">
      </el-table-column>
      <el-table-column label="服务起始日期">
        <template slot-scope="{ row }">
          {{row.serviceType === 2 ? (row.takeoffTime || '未开始') : ''}}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="100">
        <template slot-scope="scope">
          <el-popconfirm
            v-if="scope.row.status === 1"
            title="确认删除吗?"
            @onConfirm="deleteOrder(scope.row, 3, scope.$index)"
          >
            <el-button type="text" slot="reference" size="small">删除订单</el-button>
          </el-popconfirm>
          <el-popconfirm
            v-if="scope.row.status === 2"
            title="确认已经提货了吗?"
            @onConfirm="updateStatus(scope.row, 3)"
          >
            <el-button type="text" slot="reference" size="small">确认提货</el-button>
          </el-popconfirm>
          <el-popconfirm
            v-if="scope.row.status === 2 || scope.row.status === 9"
            title="确认退款吗?"
            @onConfirm="withdrawBack(scope.row, 10)"
          >
            <el-button type="text" slot="reference" size="small">申请退款</el-button>
          </el-popconfirm>
          <template v-if="scope.row.status === 3">
            <el-popconfirm
              v-if="!scope.row.isOverTime"
              title="确认已经归还了吗?"
              @onConfirm="updateStatus(scope.row, 4)"
            >
              <el-button type="text" slot="reference" size="small">确认归还</el-button>
            </el-popconfirm>
            <el-popconfirm
              v-else
              title="确认结单吗?"
              @onConfirm="updateStatus(scope.row, 11)"
            >
              <el-button type="text" slot="reference" size="small">确认结单</el-button>
            </el-popconfirm>
          </template>
          <el-popconfirm
            v-if="scope.row.status === 4 || scope.row.status === 6"
            title="确认完成吗?"
            @onConfirm="completeOrder(scope.row, 5)"
          >
            <el-button type="text" slot="reference" size="small">确认完成</el-button>
          </el-popconfirm>
          <el-popconfirm
            v-if="scope.row.status === 4"
            :title="`确认取消${scope.row.type == 1 ? '归还' : '预约'}吗?`"
            @onConfirm="scope.row.type == 1 ? cancelReturn(scope.row, 3) : cancelOrder(scope.row, 7)"
          >
            <el-button type="text" slot="reference" size="small">取消{{scope.row.type == 1 ? '归还' : '预约'}}</el-button>
          </el-popconfirm>
          <el-popconfirm
            v-if="scope.row.status === 9"
            title="确认已经发货了吗?`"
            @onConfirm="updateStatus(scope.row, 8)"
          >
            <el-button type="text" slot="reference" size="small">确认发货</el-button>
          </el-popconfirm>
          <el-popconfirm
            v-if="scope.row.status === 9"
            title="确认已经配送完成了吗?`"
            @onConfirm="updateStatus(scope.row, 3)"
          >
            <el-button type="text" slot="reference" size="small">配送完成</el-button>
          </el-popconfirm>
          <el-popconfirm
            v-if="scope.row.status === 8 || scope.row.status === 9"
            :title="`确认取消订单吗?`"
            @onConfirm="cancelOrder(scope.row, 7)"
          >
            <el-button type="text" slot="reference" size="small">取消订单</el-button>
          </el-popconfirm>
          <el-button @click="showAudit(scope.row)" type="text" size="small">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      :page-size="payload.pageSize"
      @current-change="onPageChange"
      :total="payload.total">
    </el-pagination>
    <order-info :info="currentOrderInfo" ref="orderInfo"/>
  </div>
</template>

<script>
import OrderInfo from '@/components/OrderInfo'
import numeral from 'numeral'
export default {
  name: 'OrderManage',
  components: {OrderInfo},
  data () {
    return {
      loading: true,
      formInline: {
        orderNumber: '',
        status: null,
        nickName: ''
      },
      payload: {
        current: 1,
        pageSize: 10,
        total: 10
      },
      list: [],
      currentOrderInfo: {},
      orderStatus: ['待支付', '待提货', '待归还', '待确认', '已完成', '待完成', '已取消', '配送中', '需配发', '已退款', '已超时']
    }
  },
  methods: {
    searchShops () {
      this.payload.current = 1
      this.getShopList()
    },
    getShopList () {
      const shopInfo = JSON.parse(localStorage.getItem('shopInfo'))

      this.loading = true
      let query = {}
      let orderNumber = this.formInline.orderNumber.trim()
      if (orderNumber) query.orderNumber = orderNumber
      if (this.formInline.status) query.status = this.formInline.status
      if (this.formInline.nickName) query.nickName = this.formInline.nickName
      if (this.formInline.startDate) query.startDate = this.dateFormat(this.formInline.startDate)
      if (this.formInline.endDate) query.endDate = this.dateFormat(this.formInline.endDate) + ' 23:59:59'
      query.userId = shopInfo.userId
      this.$http.post(`http://${process.env.NODE_ENV === 'development' ? 'localhost:9009' : 'qiucc.com'}/rentmall/manage/order/list`, {
        query,
        form: {},
        pagination: {
          current: this.payload.current,
          pageSize: this.payload.pageSize
        }
      }).then(res => {
        if (res.body.code === 200) {
          res.body.body.body.map(item => {
            item.statusWord = this.orderStatus[item.status - 1]
            item.payTotal = numeral(item.payTotal || 0).divide(100).format('0.00')
          })
          this.list = res.body.body.body
          this.payload.total = res.body.body.total
        } else {
          this.$message({
            message: '获取数据失败',
            type: 'warning'
          })
        }
      }).catch(err => {
        console.error(err)
      }).finally(() => {
        this.loading = false
      })
    },
    onPageChange (current) {
      this.payload.current = current
      this.getShopList()
    },
    withdrawBack (current, status) {
      this.loading = true
      this.$http.get(`${this.ApiUrls.withdrawBack}/${current.orderNumber}`).then(res => {
        if (res.body.code === 200) {
          this.$message.success('退款成功')
          current.status = status
          current.statusWord = this.orderStatus[status - 1]
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('操作失败')
      }).finally(() => {
        this.loading = false
      })
    },
    deleteOrder (current, status, index) {
      this.loading = true
      this.$http.post(this.ApiUrls.deleteOrder, {
        query: {
          orderNumber: current.orderNumber
        }
      }).then(res => {
        if (res.body.code === 200) {
          this.$message.success('操作成功')
          this.list.splice(index, 1)
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('操作失败')
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 更新订单状态
     * @param {*} current 当前数据
     * @param {Number} status 要改变成的状态
     */
    updateStatus (current, status) {
      this.loading = true
      this.$http.post(this.ApiUrls.updateOrder, {
        query: {},
        pagination: {},
        form: {
          orderNumber: current.orderNumber,
          status: status
        }
      }).then(res => {
        if (res.body.code === 200) {
          this.$message.success('操作成功')
          current.status = status
          current.statusWord = this.orderStatus[status - 1]
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('操作失败')
      }).finally(() => {
        this.loading = false
      })
    },
    completeOrder (current, status) {
      this.loading = true
      this.$http.post(`${this.ApiUrls.completeOrder}/${current.orderNumber}`).then(res => {
        if (res.body.code === 200) {
          this.$message.success('操作成功')
          current.status = status
          current.statusWord = this.orderStatus[status - 1]
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('操作失败')
      }).finally(() => {
        this.loading = false
      })
    },
    cancelReturn (current, status) {
      this.loading = true
      this.$http.get(`${this.ApiUrls.cancelReturn}/${current.orderNumber}`).then(res => {
        if (res.body.code === 200) {
          this.$message.success('操作成功')
          current.status = status
          current.statusWord = this.orderStatus[status - 1]
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('操作失败')
      }).finally(() => {
        this.loading = false
      })
    },
    cancelOrder (current, index) {
      this.loading = true
      this.$http.get(`${this.ApiUrls.cancelOrder}/${current.orderNumber}`).then(res => {
        if (res.body.code === 200) {
          this.$message.success('操作成功')
          current.status = status
          current.statusWord = this.orderStatus[status - 1]
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('操作失败')
      }).finally(() => {
        this.loading = false
      })
    },
    showAudit (rowData) {
      this.currentOrderInfo = rowData
      this.$refs.orderInfo.showShopDetail(rowData.orderNumber)
    },
    // 时间格式化
    dateFormat (updateTime) {
      var t = new Date(updateTime)
      var year = t.getFullYear()
      var month = t.getMonth() + 1
      var day = t.getDate()
      var newTime = year + '-' +
          (month < 10 ? '0' + month : month) + '-' +
          (day < 10 ? '0' + day : day)
      return newTime
    }
  },
  mounted () {
    this.getShopList()
  }
}
</script>

<style lang="less" scoped>
.col {
  display: flex;
  span {
    flex-shrink: 0;
    padding-right: 20px;
    line-height: 40px;
  }
}
.pagination {
  padding-top: 30px;
  margin-left: auto;
  display: table;
}
</style>
